import { createRouter, createWebHashHistory } from 'vue-router'
import { cache } from "@/utils/cache";
import { refreshScrollTop, inArray } from "@/utils/tool";
// 页面加载进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({
  easing: 'ease',  // 动画方式    
  speed: 500,  // 递增进度条的速度    
  showSpinner: false, // 是否显示加载ico    
  trickleSpeed: 200, // 自动递增间隔    
  minimum: 0.3 // 初始化时的最小百分比
})

// 读取环境配置
const AppConfig = window.AppConfig;

// 404页面
const notFound = {
  path: '/404',
  name: '404',
  meta: {
    title: '404-页面未找到',
    keepAlive: true,
    icon: '404',
    permission: ['/404']
  },
  component: () => import('@/exception/404.vue')
}
// 登录页面
const notLogin = {
  path: AppConfig.LOGIN_PATH,
  name: 'notLogin',
  meta: {
    title: '登录',
    keepAlive: true,
    icon: 'login',
    permission: [AppConfig.LOGIN_PATH]
  },
  component: () => import('@/views/user/Login.vue')
}
// 路由
const routes = [
  {
    path: '/',
    name: '/',
    component: () => import('@/layouts/BaseView.vue'),
    children: [
      notFound,
    ]
  },
  notFound,
  notLogin,
]
const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior() {
    return { x: 0, y: 0 }
  }
})

// 监控路由
router.beforeEach((to, from, next) => {
  // 每次切换页面时，调用进度条
  NProgress.start();

  // 更新页面title
  let page_title = '';
  try {
    page_title = to.meta.title;
  } catch (e) {
    page_title = '（没有配置meta.title名）';
  }
  if (page_title) {
    document.title = page_title;
  } else {
    document.title = AppConfig.APP_NAME;
  }

  if (to.matched.length === 0) {  // 未匹配到路由
    return next('/404');
  } else { // 匹配到路由
    refreshScrollTop();
    // 是否在免登路由地址白名单列表
    const noLoginPath = AppConfig.UNLOGIN_LIST;
    if (inArray(to.path, noLoginPath)) {
      return next();
    }
    // 验证是否登录
    if (!cache(AppConfig.BASE_API_TOKEN_NAME)) {
      cache(AppConfig.BASE_API_TOKEN_NAME, null);
      return next(AppConfig.LOGIN_PATH);
    }
    return next();
  }
});
// 路由进入
router.afterEach(() => {
  // 在即将进入新的页面组件前，关闭掉进度条
  NProgress.done()
})

export default router